﻿using NHibernate;
using NHibernate.Criterion;
using System.Collections.Generic;

namespace Golf.DataLayer
{
    using Core;

    public class PlayerRepository : RepositoryBase, IPlayerRepository
    {
        public IEnumerable<Player> Find(string forename, string surname)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(Player));
                criteria.Add(Expression.Like("Forename", forename, MatchMode.Anywhere));
                criteria.Add(Expression.Like("Surname", surname, MatchMode.Anywhere));
                criteria.AddOrder(Order.Asc("Surname"));
                criteria.AddOrder(Order.Asc("Forename"));
                return criteria.List<Player>();
            }
        }

        public Player Get(int id)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                return session.Get<Player>(id);
            }
        }

        public IEnumerable<Player> GetAll()
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(Player));
                return criteria.List<Player>();
            }
        }

        public void Save(Player player)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                session.SaveOrUpdate(player);
                session.Flush();
            }
        }

        public void Delete(int id)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                session.Delete(Get(id));
                session.Flush();
            }
        }
    }
}